<template>
  <div class="classification-page">
    <div class="toolbar formSearch">
      <el-button type="success" @click="addBar">添加一级类别</el-button>
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      style="width: 100%"
      border
      row-key="id"
      :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
      :tree-props="{ children: 'childs' }"
      class="dataTable"
    >
      <el-table-column prop="categoryName" label="服务类别" />
      <el-table-column prop="status" label="操作">
        <template #default="scope">
  
          <el-button
            type="primary"
            link
            @click.native.prevent="updateRow(scope.row)"
          >编辑</el-button>
          <el-popconfirm title="确认删除？" @confirm="deleteRow(scope.row)">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="formParams.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="formParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      background
      :total="total"
      style="margin: 12px 0;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <EditDialog
      v-model:dialogVisible="editDialogVisible"
      :params="editDialogParams"
      @success="getAll(formParams)"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  getCommodityClassList,
  deleteCommodityClass
} from '@/api/commodityClassApi'
import EditDialog from './Edit.vue'

const tableLoading = ref(false)
const formParams = reactive({
  page: 1,
  pageSize: 10,
})
const total = ref(0)
const tableData = ref<any[]>([])
// dialog变量已替换为editDialogVisible和editDialogParams

const editDialogVisible = ref(false)
const editDialogParams = ref({})

onMounted(() => {
  // 直接调用getAll并传递分页参数，避免重复请求
  getAll(formParams)
})

function handleSizeChange (val: number) {
  formParams.pageSize = val
  getAll(formParams)
}

function handleCurrentChange (val: number) {
  formParams.page = val
  getAll(formParams)
}

function fetch (config: any) {
  const { limit, page } = config
  formParams.page = page || 1
  formParams.pageSize = limit || 10
  getProductCategory()
}

// edit组件引用已移除

function addBar () {
  editDialogVisible.value = true
  editDialogParams.value = {}
}

// editClose函数已移除

// 编辑
function updateRow (row: any) {
  editDialogVisible.value = true
  editDialogParams.value = { id: row.id || row.classifyId }
}

// 查看
function checkRow (row: any) {
  editDialogVisible.value = true
  editDialogParams.value = { id: row.id || row.classifyId }
}

// 删除
async function deleteRow (row: any) {
  ElMessageBox.confirm('此操作将永久删除该类别, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteCommodityClass({ oneClassifyId: row.id || row.classifyId }).then((res: any) => {
        if (res.code === '' || res.code === '200') {
          ElMessage({
            type: 'success',
            message: '删除成功!',
          })
        } else {
          ElMessage({
            type: 'error',
            message: res.message || '删除失败!',
          })
        }
        getAll(formParams)
      }).catch(error => {
        console.error('删除失败:', error)
        ElMessage.error('删除失败!')
        getAll(formParams)
      })
    })
    .catch(() => {})
}

// 初始加载数据
  function getProductCategory () {
    getAll()
  }

function getAll (formParams: any = {}) {
  tableLoading.value = true
  getCommodityClassList(formParams).then((res: any) => {
    try {
      // 确保数据格式正确，兼容不同的API返回格式
      if (res.data) {
        let resultList = []
        // 判断API返回的数据结构
        if (Array.isArray(res.data)) {
          // 如果返回的是数组
          resultList = res.data
        } else if (res.data.list) {
          // 如果返回的是带有list属性的对象
          resultList = res.data.list
        } else {
          // 其他情况
          resultList = [res.data]
        }
        
        // 处理字段映射，确保数据结构一致
        tableData.value = resultList.map((item: any) => ({
          ...item,
          id: item.id || item.classifyId,
          categoryName: item.categoryName || item.classifyName,
          childs: item.childs || []
        }))
        
        // 设置总数
        total.value = res.data.total || resultList.length
      } else {
        tableData.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('数据处理错误:', error)
      tableData.value = []
      total.value = 0
    }
  }).catch((error: any) => {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    total.value = 0
  }).finally(() => {
    tableLoading.value = false
  })
}
</script>

<style lang="scss" scoped>
.classification-page {
  padding: 20px;
  margin-top: 20px;
  background-color: #FFFFFF;
  .toolbar {
    margin-bottom: 15px;
    text-align: right;
  }
}
</style>
